#!/usr/bin/env python3
"""详细调试对话搜索问题"""

import asyncio
import sys
import os
sys.path.append(os.path.dirname(os.path.abspath(__file__)))

from src.config import load_config
from src.database.chromadb_client import ChromaDBClient
from src.database.mongodb_client import MongoDBClient

async def debug_conversation_search_detailed():
    """详细调试对话搜索问题"""
    print("=== 详细调试对话搜索问题 ===")
    
    try:
        # 加载配置
        config = load_config()
        
        # 初始化 ChromaDBClient
        chromadb_client = ChromaDBClient(config)
        await chromadb_client.connect()
        
        print("✅ ChromaDBClient 连接成功")
        
        # 初始化 MongoDB 客户端
        mongodb_client = MongoDBClient(config)
        await mongodb_client.connect()
        
        print("✅ MongoDB 连接成功")
        
        # 搜索参数
        query = "王者荣耀"
        user_id = "default_user"
        limit = 5
        
        print(f"\n1. ChromaDB 向量搜索...")
        print(f"   查询: {query}")
        print(f"   用户ID: {user_id}")
        print(f"   限制: {limit}")
        
        # 执行向量搜索
        vector_results = await chromadb_client.search_conversations(query, user_id, limit * 2)
        
        print(f"   搜索结果数量: {len(vector_results)}")
        
        if not vector_results:
            print("   ❌ ChromaDB 搜索无结果")
            return
        
        # 分析搜索结果
        print(f"\n2. 分析 ChromaDB 搜索结果...")
        conversation_scores = {}
        
        for i, result in enumerate(vector_results):
            print(f"   结果 [{i+1}]:")
            print(f"     conversation_id: {result.get('conversation_id')}")
            print(f"     message_id: {result.get('message_id')}")
            print(f"     similarity: {result.get('similarity')}")
            print(f"     content: {result.get('content', '')[:100]}...")
            
            conv_id = result.get('conversation_id')
            if conv_id:
                if conv_id not in conversation_scores:
                    conversation_scores[conv_id] = {
                        'conversation_id': conv_id,
                        'max_similarity': 0,
                        'relevant_messages': []
                    }
                
                similarity = result.get('similarity', 0)
                if similarity > conversation_scores[conv_id]['max_similarity']:
                    conversation_scores[conv_id]['max_similarity'] = similarity
                
                conversation_scores[conv_id]['relevant_messages'].append(result)
        
        print(f"\n   按对话ID分组后的结果:")
        for conv_id, score_data in conversation_scores.items():
            print(f"     对话ID: {conv_id}")
            print(f"     最高相似度: {score_data['max_similarity']}")
            print(f"     相关消息数: {len(score_data['relevant_messages'])}")
        
        print(f"\n3. 检查 MongoDB 中的对话记录...")
        
        final_results = []
        for conv_id, score_data in conversation_scores.items():
            print(f"\n   检查对话ID: {conv_id}")
            
            # 使用 MongoDB 客户端查找对话
            conv_info = await mongodb_client.get_conversation(conv_id)
            
            if conv_info:
                print(f"     ✅ 在 MongoDB 中找到对话")
                print(f"     标题: {conv_info.get('title', 'N/A')}")
                print(f"     用户ID: {conv_info.get('user_id', 'N/A')}")
                print(f"     状态: {conv_info.get('status', 'N/A')}")
                print(f"     创建时间: {conv_info.get('created_at', 'N/A')}")
                print(f"     消息数量: {conv_info.get('message_count', 0)}")
                
                # 添加到最终结果
                final_results.append({
                    'conversation_id': conv_id,
                    'title': conv_info.get('title', ''),
                    'user_id': conv_info.get('user_id'),
                    'created_at': conv_info.get('created_at'),
                    'updated_at': conv_info.get('updated_at'),
                    'message_count': conv_info.get('message_count', 0),
                    'similarity': score_data['max_similarity'],
                    'relevant_messages': score_data['relevant_messages'][:3]
                })
            else:
                print(f"     ❌ 在 MongoDB 中未找到对话")
                
                # 检查 MongoDB 中是否有任何对话记录
                collection = mongodb_client.get_collection('conversations')
                
                # 尝试不同的查询方式
                print(f"     尝试不同的查询方式...")
                
                # 1. 按 conversation_id 查询
                conv_by_id = await collection.find_one({'conversation_id': conv_id})
                if conv_by_id:
                    print(f"       ✅ 按 conversation_id 找到: {conv_by_id.get('title')}")
                else:
                    print(f"       ❌ 按 conversation_id 未找到")
                
                # 2. 按 _id 查询
                try:
                    from bson import ObjectId
                    if ObjectId.is_valid(conv_id):
                        conv_by_object_id = await collection.find_one({'_id': ObjectId(conv_id)})
                        if conv_by_object_id:
                            print(f"       ✅ 按 _id 找到: {conv_by_object_id.get('title')}")
                        else:
                            print(f"       ❌ 按 _id 未找到")
                    else:
                        print(f"       ❌ 不是有效的 ObjectId: {conv_id}")
                except Exception as e:
                    print(f"       ❌ ObjectId 查询失败: {e}")
                
                # 3. 查看所有对话记录
                all_conversations = await collection.find({}).to_list(length=10)
                print(f"       MongoDB 中总对话数: {await collection.count_documents({})}")
                
                if all_conversations:
                    print(f"       前几个对话记录:")
                    for j, conv in enumerate(all_conversations[:3]):
                        print(f"         [{j+1}] _id: {conv.get('_id')}")
                        print(f"             conversation_id: {conv.get('conversation_id')}")
                        print(f"             title: {conv.get('title')}")
                        print(f"             user_id: {conv.get('user_id')}")
        
        # 按相似度排序
        final_results.sort(key=lambda x: x['similarity'], reverse=True)
        
        print(f"\n4. 最终搜索结果...")
        print(f"   结果数量: {len(final_results)}")
        
        if final_results:
            for i, result in enumerate(final_results[:limit]):
                print(f"   [{i+1}] 对话ID: {result['conversation_id']}")
                print(f"       标题: {result['title']}")
                print(f"       相似度: {result['similarity']}")
                print(f"       用户ID: {result['user_id']}")
        else:
            print(f"   ❌ 无最终结果")
        
        print(f"\n✅ 详细调试完成")
        
    except Exception as e:
        print(f"❌ 调试失败: {e}")
        import traceback
        traceback.print_exc()

if __name__ == "__main__":
    asyncio.run(debug_conversation_search_detailed())